/*
Copyright 2011 Mohit Shah
    
This file is part of SoundBlogs.

SoundBlogs is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.

SoundBlogs is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with SoundBlogs.  If not, see <http://www.gnu.org/licenses/>.
*/

package com.application.soundblogs;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

import org.apache.http.util.ByteArrayBuffer;

import com.application.soundblogs.MyLocation;
import com.application.soundblogs.MyLocation.LocationResult;

import android.app.Activity;
import android.content.Intent;
import android.content.res.Resources;
import android.location.Location;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.Spinner;
import android.widget.Toast;

public class ChooseAudio extends Activity {
	private boolean isRecording, isPlaying, isPlayEligible, isPlayEligibleRecorder;
    private ExtAudioRecorder extaudiorecorder;
    private Button record = null;
    private Button play = null;
    private CharSequence[] urls, paths;
    MediaPlayer mPlayer = null;
    int index=0;
    private final static String LAT = "lat";
	private final static String LON = "lon";
	private final static String AUDIO_SAMPLE = "sample";
	private final static String AUDIO_SOURCE = "source";
	String audio_url = null;
	double lat,lon;
	int audio_source = 0;
	int audio_sample = 0;
	boolean[] hasPlayed = new boolean[4];
	private AsyncTask<Void,Integer,Void> audio_task, record_start, record_stop, proceed_next = null;
	@Override
	public void onCreate(Bundle savedInstanceState){
		super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_CUSTOM_TITLE);		
		setContentView(R.layout.audio);
		getWindow().setFeatureInt(Window.FEATURE_CUSTOM_TITLE, R.layout.mytitle);
		record = (Button) findViewById(R.id.recordbutton);
		record.setText("Start Recording");
		record.setOnClickListener(new record_click());
		isRecording=false;
		play = (Button) findViewById(R.id.playbutton);
		play.setText("Start Playing");
		play.setOnClickListener(new play_click());
		isPlaying=false;
		isPlayEligible=false;
		isPlayEligibleRecorder=false;
		Button next = (Button) findViewById(R.id.nextbutton);
		next.setText("Proceed further");		
		next.setOnClickListener(new next_click());
		Spinner spinner = (Spinner) findViewById(R.id.spinner);
	    ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(
	            this, R.array.audio_array, android.R.layout.simple_spinner_item);
	    adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
	    spinner.setAdapter(adapter);		
	    spinner.setOnItemSelectedListener(new MyOnItemSelectedListener());
        MyLocation myLocation = new MyLocation();
    	myLocation.getLocation(ChooseAudio.this, locationResult);
    	Log.d("LocationTest", "GetLocation activated");
    	Resources res = getResources();
    	urls = res.getTextArray(R.array.url_array);
    	paths = res.getTextArray(R.array.audio_files);
    	hasPlayed[0]=true;
	}
	public class MyOnItemSelectedListener implements OnItemSelectedListener {

	    public void onItemSelected(AdapterView<?> parent,
	        View view, int pos, long id) {
	    	if(pos!=0) {
	    		index=pos;
	    		isPlayEligible=true;
	    		audio_source = 1;
	    		audio_sample = index;
	    	}
	    	else {
	    		isPlayEligible=false;
	    	}
	    }
	    public void onNothingSelected(AdapterView parent) {
	      // Do nothing.
	    }
	}
    private void startRecording() {
        isRecording=true;
        isPlayEligibleRecorder=false;
    	extaudiorecorder = ExtAudioRecorder.getInstanse(false);
        extaudiorecorder.setOutputFile("/sdcard/test.wav");
    	extaudiorecorder.prepare();
    	extaudiorecorder.start();
    	//record.setText("Stop Recording");
    }

    private void stopRecording() {
    	extaudiorecorder.stop();
    	extaudiorecorder.release();
    	isRecording=false;
    	isPlayEligibleRecorder=true;
    	audio_source = 0;
    	audio_sample = 0;
    	//record.setText("Start Recording");
    }
    private void downloadFile(String url, String path) {
    	HttpURLConnection ucon;
    	try {
            URL location = new URL(url);
            File file = new File(path);

            long startTime = System.currentTimeMillis();
            Log.d("AudioDownload", "download begining");
            Log.d("AudioDownload", "download url:" + url);
            Log.d("AudioDownload", "downloaded file name:" + path);
            /* Open a connection to that URL. */
            ucon = (HttpURLConnection) location.openConnection();

            /*
             * Define InputStreams to read from the URLConnection.
             */
            InputStream is = ucon.getInputStream();
            BufferedInputStream bis = new BufferedInputStream(is);

            /*
             * Read bytes to the Buffer until there is nothing more to read(-1).
             */
            ByteArrayBuffer baf = new ByteArrayBuffer(50);
            int current = 0;
            while ((current = bis.read()) != -1) {
                    baf.append((byte) current);
            }

            /* Convert the Bytes read to a String. */
            FileOutputStream fos = new FileOutputStream(file);
            fos.write(baf.toByteArray());
            fos.close();
            Log.d("AudioDownload", "download ready in"
                            + ((System.currentTimeMillis() - startTime) / 1000)
                            + " sec");

    } catch (IOException e) {
            Log.d("A", "Error: " + e);
    }

}    	
    
    private void startPlaying(){
    	if(isPlayEligible==true && isPlayEligibleRecorder==true){
            mPlayer = new MediaPlayer();
            try {
            	Uri.Builder b = Uri.parse(urls[index].toString()).buildUpon();
            	String url = b.build().toString(); 
//Added 06/29
            	b = Uri.parse(paths[index].toString()).buildUpon();
            	String path = b.build().toString(); 
            	downloadFile(url,path);
//
            	mPlayer.setDataSource(path);
            	mPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
                mPlayer.prepare();
                mPlayer.start();
                isPlaying=true;
                audio_url = new String(url);
                hasPlayed[index]=true;
                //play.setText("Stop Playing");
            } catch (IOException e) {
                Log.e("Player", "prepare() failed in 0");
            }
    	}
    	else if(isPlayEligible==true && isPlayEligibleRecorder==false){
            mPlayer = new MediaPlayer();
            try {
            	Uri.Builder b = Uri.parse(urls[index].toString()).buildUpon();
            	String url = b.build().toString();
//Added 06/29
            	b = Uri.parse(paths[index].toString()).buildUpon();
            	String path = b.build().toString(); 
            	downloadFile(url,path);
//
            	mPlayer.setDataSource(path);
            	mPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
                mPlayer.prepare();
                mPlayer.start();
                isPlaying=true;
                audio_url = new String(url);
                hasPlayed[index]=true;
                //play.setText("Stop Playing");
            } catch (IOException e) {
                Log.e("Player", "prepare() failed in 1");
            }
    	}
    	else if(isPlayEligible==false && isPlayEligibleRecorder==true){
            mPlayer = new MediaPlayer();
            try {
            	Uri.Builder b = Uri.parse("/sdcard/test.wav").buildUpon();
            	String url = b.build().toString(); 
            	mPlayer.setDataSource(url);
            	mPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
            	mPlayer.prepare();
                mPlayer.start();
                //play.setText("Stop Playing");
                audio_url = new String(url);
                isPlaying=true;
            } catch (IOException e) {
                Log.e("Player", "prepare() failed in 2");
            }
    	}
    	else {
    		//Toast.makeText(getApplicationContext(), "Please choose input audio", Toast.LENGTH_LONG).show();
    		isPlaying=false;
    	}
    }
    
    private void stopPlaying(){
        mPlayer.release();
        mPlayer = null;
        //play.setText("Start Playing");
        isPlaying=false;
    }
    private void taskfinished() {
		if(isRecording) {
	    	extaudiorecorder.stop();
	    	extaudiorecorder.release();
			}
			if(isPlaying) {
	        mPlayer.release();
	        mPlayer = null;
			}    	
    	Intent intent = new Intent(ChooseAudio.this,BlogMap.class);
		intent.putExtra(AUDIO_SAMPLE, audio_sample);
		intent.putExtra(AUDIO_SOURCE, audio_source);
		intent.putExtra(LAT, lat);
		intent.putExtra(LON, lon);
		ChooseAudio.this.startActivity(intent);
    }
	private class record_click implements View.OnClickListener{
		@Override
		public void onClick(View v){
			if(!isRecording){
				Toast.makeText(getApplicationContext(), "Recording Started", Toast.LENGTH_LONG).show();
				//startRecording();
				record.setText("Stop Recording");
				record_start = new StartRecord().execute();
			}
			else {
				Toast.makeText(getApplicationContext(), "Recording Stopped", Toast.LENGTH_LONG).show();
				//stopRecording();
				record.setText("Start Recording");
				record_stop = new StopRecord().execute();
			}			
		}
	};
	private class play_click implements View.OnClickListener{
		@Override
		public void onClick(View v){
			if(!isPlaying) {
				Toast.makeText(getApplicationContext(), "Playing Audio...", Toast.LENGTH_LONG).show();
				//startPlaying();
				play.setText("Stop Playing");
				audio_task = new PlayAudio().execute();
			}
			else {
				play.setText("Start Playing");
				stopPlaying();
			}
			
		}
	};
	private class next_click implements View.OnClickListener{
		@Override
		public void onClick(View v){
			if(isPlayEligible==true || isPlayEligibleRecorder==true){
				if(hasPlayed[audio_sample]==false) {
					Toast.makeText(getApplicationContext(), "Proceeding...Please Wait", Toast.LENGTH_LONG).show();
					proceed_next = new DownloadBeforeProceed().execute();
				}
				else {
					Toast.makeText(getApplicationContext(), "Proceeding...Please Wait", Toast.LENGTH_LONG).show();					
					taskfinished();
				}
			}
			else {
				Toast.makeText(getApplicationContext(), "Please choose input audio", Toast.LENGTH_LONG).show();
			}
		}
	};
    public LocationResult locationResult = new LocationResult(){
        @Override
        public void gotLocation(final Location location){
            Log.d("LocationTest","Got Location");
            Log.d("LocationTest",location.getLatitude()+"");
            Log.d("LocationTest",location.getLongitude()+"");
            lat = location.getLatitude();
            lon = location.getLongitude();
            Toast.makeText(getApplicationContext(), "Captured your current location", Toast.LENGTH_SHORT).show();
        	//Got the location!
        };
    };
    private class PlayAudio extends AsyncTask<Void,Integer,Void> {
    	@Override
    	public Void doInBackground(Void... params){
    		Void ret = null;
    		startPlaying();
    		return ret;
    	}
    }
    private class StartRecord extends AsyncTask<Void,Integer,Void> {
    	@Override
    	public Void doInBackground(Void... params){
    		Void ret = null;
    		startRecording();
    		return ret;
    	}
    }
    private class StopRecord extends AsyncTask<Void,Integer,Void> {
    	@Override
    	public Void doInBackground(Void... params){
    		Void ret = null;
    		stopRecording();
    		return ret;
    	}
    }
    private class DownloadBeforeProceed extends AsyncTask<Void,Integer,Void> {
    	@Override
    	public Void doInBackground(Void... params){
    		Void ret = null;
    		downloadFile((urls[audio_sample].toString()),(paths[audio_sample].toString()));
    		return ret;
    	}
    	protected void onPostExecute(Void result){
    		taskfinished();
    	}
    }

}
